
import { Form, Input, Table, Select, DatePicker, Space, Button, Modal } from "antd";
import { useEffect, useState } from "react";
import dayjs from "dayjs";
import customerApi from "../../api/customer";
const { confirm } = Modal;

export default function CustomList() {
  const [delIds, setDelIds] = useState([]);

  const [searchForm] = Form.useForm();

  const [isLoading, setIsLoading] = useState(false);

  const [isModalOpen, setIsModalOpen] = useState(false);

  const [editId, setEditId] = useState();

  const [editForm] = Form.useForm();


  const handleOk = async () => {
    const data = editForm.getFieldsValue();
    await customerApi.add(data);
    setFilterParams({ ...filterParams, pageNum: 1 })
    editForm.resetFields();
    setIsModalOpen(false)
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    editForm.resetFields();
  };

  const openEdit = async (record) => {
    const data = await customerApi.getByKey(record)
    if (data.createDate) {
      data.createDate = dayjs(data.createDate);
    }
    setIsModalOpen(true);
    setEditId(record.customerId)
    editForm.setFieldsValue(data);

  };

  const searchData = (searchForm) => {
    setFilterParams({ ...filterParams, ...searchForm })
  }

  const reset = () => {
    searchForm.resetFields();
    setFilterParams({
      pageNum: 1,
      pageSize: 3,
      sort: "desc",
      order: "createDate",
    });
  };

  const [filterParams, setFilterParams] = useState({
    pageNum: 1,
    pageSize: 3,
    sort: "desc",
    order: "createDate",
  });

  const [dataSource, setDataSource] = useState([]);

  const [total, setTotal] = useState(0);

  const paginationChange = (pageNum, pageSize) => {
    setFilterParams({
      ...filterParams,
      pageNum
    })
  }

  /**
   * 过滤参数发生改变,重新调用接口
   */
  useEffect(() => { getData() }, [filterParams]);

  /**
   * 获取列表数据
   */
  const getData = async () => {
    setIsLoading(true);
    const data = await customerApi.getList(filterParams);
    data.records.forEach((item) => {
      item.key = item.customerId;
    });

    setDataSource(data.records);
    setTotal(data.total);
    setIsLoading(false);
  };




  const columns = [
    {
      title: "序号",
      // dataSource数组里面对应要展示的字段
      dataIndex: "customerId",
      key: "customerId",
      align: 'center',
      render: (text, record, index) => <a>{index + 1}</a>,
    },
    {
      title: "客户编号",
      // dataSource数组里面对应要展示的字段
      dataIndex: "customerId",
      key: "customerId",
      align: 'center',

    },
    {
      title: "客户名称",
      dataIndex: "customerName",
      align: 'center',
      key: "customerName",
    },
    {
      title: "客户地址",
      dataIndex: "address",
      align: 'center',
      key: "address",
    },
    {
      title: "更新日期",
      align: 'center',
      dataIndex: "modifyDate",
      key: "customerId",
      render: (text, record) => (
        <div>
          {text && dayjs(text).format('YYYY-MM-DD  HH:mm:ss')}
        </div>
      )
    },
    {
      title: "操作",
      align: 'center',
      dataIndex: "id",
      render: (text, record) => (
        <Space>
          <Button onClick={() => openEdit(record)}>编辑</Button>
          <Button danger onClick={() => delByKeys(record.customerId)}>删除</Button>
        </Space>
      ),
    },
  ];

  const onSelectChange = (rowKeys) => {
    setDelIds(rowKeys);
  };
  const delByKeys = (id) => {
    confirm({
      title: "确定要删除吗？",
      async onOk() {
        const ids = id ? [id] : delIds;
        await customerApi.delByKeys(ids)
        setFilterParams({ ...filterParams, pageNum: 1 })
        setDelIds([])
      }
    })
  }
  return (
    <div>
      <Space>
        <Space>
          <Button onClick={getData}>刷新</Button>
          <Button type="primary" onClick={() => setIsModalOpen(true)}>新增</Button>
          <Button danger onClick={() => delByKeys()} disabled={!delIds.length}>删除</Button>
        </Space>
        <Form layout="inline" form={searchForm} onFinish={searchData}>
          <Form.Item name="customerName">
            <Input placeholder="请输入客户名称查询">
            </Input>
          </Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">搜索</Button>
            <Button onClick={() => reset()}>重置</Button>
          </Space>
        </Form>

      </Space>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={{
          current: filterParams.pageNum,
          pageSize: filterParams.pageSize,
          showQuickJumper: true,
          total: total,
          onChange: paginationChange
        }}
        rowSelection={{
          type: "checkbox",
          onChange: onSelectChange,
        }}
      >

      </Table>

      <Modal title={editId ? "编辑" : "新增"} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} >
        <Form form={editForm} >
          <Form.Item name="customerId" label="主键" hidden>
            <Input />
          </Form.Item>
          <Form.Item name="customerName" label="客户名称">
            <Input />
          </Form.Item>
          <Form.Item name="address" label="地址">
            <Input />
          </Form.Item>
          <Form.Item name="createDate" label="创建日期">
            <DatePicker   format="YYYY-MM-DD HH:mm:ss"/>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}